const indexOf = require('lodash/indexOf')
const axios = require('axios')
const Dispatch = require('../dispatch/Dispatch')
const base = require('../base/baseObj')
const con = require('../../config/const')

// 并发请求队列
const allQuery = (req, res, next, query, successArr) => {
    Dispatch.all(query, res)
    .then(axios.spread( (... response) => {
        const arr = [], len = response.length
        let status = con.SUCCESS_STATUS, success = 0, failure = 0, total = len, failureIndex = -1
        for(let i = 0; i < len; i++){
            if(response[i].status == 200 && indexOf(successArr, '' + response[i].data.status) >= 0){
                success++
            } else {
                status = con.ERR_STATUS
                failure++
                if (-1 === failureIndex) {
                    failureIndex = i
                }
            }
            if(response[i].data){
                arr.push(response[i].data)
            } else {
                arr.push({})
            }
        }
        res.json({status: status, success: success, failure: failure, failureIndex: failureIndex, total: total, res: arr})
    })).catch((e, e2) =>{
        res.json(base.param_err({e, e2}, e.message))
    })

}




/*

.then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));







    .then((response, res)=>{
        const arr = [], len = response.length
        let status = con.SUCCESS_STATUS, success = 0, failure = 0, total = len, failureIndex = -1

        for(let i = 0; i < len; i++){
            if(indexOf(successArr, response[i].data.status + '') >= 0){
                success++
            } else {
                status = con.ERR_STATUS
                failure++
                if (-1 === failureIndex) {
                    failureIndex = i
                }
            }
            arr.push(response[i].data)
        }
        res.json({status: status, success: success, failure: failure, failureIndex: failureIndex, total: total, res: arr})
    }, (response, res) => {
        console.log('i:::' + i ,response)
        res.json(base.param_err(response, 'i:' + i))
    })
    .catch((e, e2) =>{
        res.json(base.param_err({e, e2}, e.message))
    })

*/






module.exports = allQuery